var changeBtn = document.getElementById("changeBtn");
var token = localStorage.getItem("token_type") + " " + localStorage.getItem("access_token");
(function($) {

	setPxPerRem();

	mui.plusReady(function() {

	});
})(mui);

mui(".mui-content").on("click", "img", function() {
	var inputEle = prev(this);
	if(this.src.indexOf("05.png") > -1) {
		this.src = "../../ui/building/images/common/04.png";
		inputEle.type = "password";
	} else {
		this.src = "../../ui/building/images/common/05.png";
		inputEle.type = "text";
	}
});

var canChange = true;
var newPwdDiv = document.getElementById("newPwdDiv");
var newPWD = document.getElementById("newPWD");

newPWD.onchange = function() {
	if(!isPasswd(this.value)) {
		showEle(newPwdDiv);
		canChange = false;
	} else {
		canChange = true;
		hiddenEle(newPwdDiv);
	}
}

var newTOWDiv = document.getElementById("newTOWDiv");
var newTOW = document.getElementById("newTOW");
newTOW.onchange = function() {
	if(!isPasswd(this.value)) {
		canChange = false;
		showEle(newTOWDiv);
	} else {

		if(this.value !== newPWD.value) {
			canChange = false;
			newTOWDiv.innerHTML = "两次输入密码不一致！"
			showEle(newTOWDiv);
		} else {
			canChange = true;
			hiddenEle(newTOWDiv);
		}
	}
}

function isPasswd(s) {
	var patrn = /^(\w){6,16}$/;
	if(!patrn.exec(s)) {
		return false
	}
	return true
}

changeBtn.addEventListener('click', function() {

	if(!canChange) {
		mui.toast("密码格式错误，请修改后再试");
		return;
	}
	var pwdOne = newPWD.value;
	var pwdTow = newTOW.value;
	var oldPwd = $('#oldPwd').val();
	if(isEmpty(oldPwd)) {
		mui.toast("请输入旧密码");
		return;
	}

	if(isEmpty(pwdOne)) {
		mui.toast("请输入新密码");
		return;
	}

	if(isEmpty(pwdTow)) {
		mui.toast("请再次输入新密码");
		return;
	}
	
	if(isHaveNet()){
		postChangePwd(token , oldPwd , pwdOne)
	} else {
		mui.toast("网络连接失败")
	}

}, false);

function postChangePwd(authorization , oldPwd , newPwd) {
	var settings = {
		url: getRequestAddressUrl("testline") + '/account/password',
		method: "POST",
		data: {
			"old_password": oldPwd,
			"new_password": newPwd
		},
		headers: {
			"accept": "application/json",
			"authorization": authorization
		}
	}

	$.ajax(settings).done(function(data) {
		if(!isEmpty(data)){
			var row = data.meta;
			if(!isEmpty(row)){
				if(row.code == 10000){
					mui.toast("密码修改成功");
					mui.back();
				}else {
					mui.toast("修改失败");
				}
			}
		}
	});
}